const jwt = require('jsonwebtoken');
const secretKey = 'itheima No1 ^_^';
const moment = require('moment'); 
//model 数据层
module.exports = class testModel extends require('./Model') {
    //查找
    static findUserList(req, res) {
        return new Promise((resolve, reject) => {
            let sql = 'select * from user'
            this.query(sql)// 调用基类的query方法往里面输入sql语句
                .then((r) => {
                    resolve(r)
                })
                .catch((e) => {
                    reject(e)
                })
        })
    }

    //查找单个信息
    static findUserListByCond(req, res) {
        return new Promise((resolve, reject) => {
            // console.log(req.body)
            let {username,password} = req.body
            let sql = 'select * from user where username=? AND password=? and status = 1'

            this.query(sql,[username,password])// 调用基类的query方法往里面输入sql语句
                .then((r) => {
                    // console.log(r)
                    resolve(r)
                })
                .catch((e) => {
                    reject(e)
                })
        })
    }

    //增加用户数据
    static addUser(req, res) {
        return new Promise((resolve, reject) => {
            console.log(req.body)
            const info = req.body
            console.log(info)
            const currentTime = moment().format('YYYY-MM-DD HH:mm:ss'); // 当前时间
            // 设置 created_time 和 updated_time
            console.log(currentTime)
            info.create_time = currentTime;
            info.update_time = currentTime;
            console.log(info)
            let sql = 'insert into user set ?'
            this.query(sql, info)
                .then((r) => {
                    resolve(r)
                })
                .catch((e) => {
                    reject(e)
                })
        })
    }

    //删除单个数据
    static deleteUser(req, res) {
        return new Promise((resolve, reject) => {
            let { id } = req.body
            let sql = 'DELETE FROM user WHERE id=?'
            this.query(sql, [id]) //单个id成为一个数组，思考如果id是多个组成数组，就可以实现批量删除
                .then((r) => {
                    resolve({ message: "id 为 " + id + ' 删除成功！' })
                })
                .catch((e) => {
                    reject({ message: "id 为 " + id + " 删除失败", reason: e })
                })
        })
    }

    //删除多个数据 可以自行思考怎么实现 选中的id 可以是多个，组成数组

    //修改
    //注意mysql配置是默认不识别大小写的，可以对mysql字段中的排序规则设置为 utf8mb4_bin 这样mysql中你要修改的字段就可以实现区分大小
    //修改
static changeUser(req, res) { 
    return new Promise((resolve, reject) => {
        let { id, sex, address, email, birth } = req.body;
        const currentTime = moment().format('YYYY-MM-DD HH:mm:ss'); // 当前时间
        let sql = 'UPDATE user SET sex=?, address=?, email=?, birth=?, updated_time=? WHERE id=?';
        this.query(sql, [sex, address, email, birth, currentTime, id])
            .then((r) => {
                console.log("success", r)
                resolve({ message: "修改成功" })
            })
            .catch((e) => {
                console.log("error", e)
                reject({ message: "修改失败" })
            })
    })
}

    //禁用用户
    static disableUser(req, res) { 
        return new Promise((resolve, reject) => {
            //sql 语句为 当name是xx的时候，把name修改为xxx
            let sql = 'update user set status=0 where id=?'
            this.query(sql, [req.body.id])
                .then((r) => {
                    resolve({ message: "禁用成功" })
                })
                .catch((e) => {
                    reject({ message:"禁用失败"})
                })
        })

    }

    static findUserDetail(req, res) {
        return new Promise((resolve, reject) => {
            console.log("req.headers",req.headers)

            const token = req.headers.authorization?.split(' ')[1];
            if (!token) {
                return res.status(401).send({ status: 0, message: 'error', errorMessage: "未提供授权令牌" });
            }

            try {
                const decoded = jwt.verify(token, secretKey);
                const id = decoded.id;
                console.log(id);
                let sql = 'SELECT * FROM user WHERE id = ?';
                this.query(sql, [id])
                    .then((r) => {
                        resolve(r);
                    })
                    .catch((e) => {
                        reject(e);
                    });
            } catch (e) {
                res.status(401).send({ status: 0, message: 'error', errorMessage: "无效的授权令牌" });
                reject(e);
            }
        });
    }

}